;(function(){
  'use strict';
  angular.module('services.omdisplay.recAbnormal')
    .factory('FileDetailServer', fileDetailServer)
    .factory('FDSelectorService', fileDetailSelector)
    .factory('FDQueryParamService', fileDetailQueryParam)
    .factory('FDViewObjService', fileDetailViewObj);
  /**
   * 文件延迟统计server
   * @param   Restangular
   * @return                service实例
   */
  function fileDetailServer(Restangular){
    return {
      fileDetailQuery:fileDetailQuery,
      moreFileDetail:moreFileDetail
    };
    /**
     * 文件延迟统计查询
     * @param     param      查询参数
     * @param     callback   回调函数
     */
    function fileDetailQuery(param,callback){
      return Restangular.all('sas/OMdisplay/reconciliationsAbnormal/fileUnreceivedStatistic').post(param).then(callback);
    }

    /**
     * 文件延迟详细情况
     * @param     param      查询参数
     * @param     callback   回调函数
     */
    function moreFileDetail(param,callback){
      return Restangular.all('sas/OMdisplay/reconciliationsAbnormal/fileUnreceivedDetail').post(param).then(callback);
    }
  }

  fileDetailServer.$inject = ['Restangular'];

  /**
   * 文件延迟统计选项集service
   * @param   COREDATA  公共数据
   * @return            service实例
   */
  function fileDetailSelector(COREDATA){
    var selector =  {
      //业务线
      channelCode:COREDATA.BUSINESSLINE,
      //省公司
      provinceCode:COREDATA.PROVINCES,
      //账期
      timeType: COREDATA.TIMETYPES
    };
    return {
      selector : selector
    };
  }
  /**
   * 文件延迟查询service
   * @param   CoreLoading        载入动画service
   * @param   RecAbnormalService 对账差异分析service
   * @param   FDSelectorService  下拉选项集service
   * @param   FileDetailServer   文件延迟统计查询请求server
   * @param   CoreService        公共方法service
   * @param   FDViewObjService   视图数据service
   * @return                     service实例
   */
  function fileDetailQueryParam(CoreLoading,RecAbnormalService,FDSelectorService,FileDetailServer,CoreService,FDViewObjService){
    var param = {};
    var date = {};
    var flag = {};
    var selector = FDSelectorService.selector;

    return {
      initParam : initParam,
      initDate : initData,
      initFlag : initFlag,
      queryFn : queryFn
    };

    function initParam(){
      param = {};
      return param;
    }

    function initData(){
      if(param.timeType){
        date = RecAbnormalService.initDate(param.timeType.timeTypeCode);
      }else{
        date = RecAbnormalService.initDate(selector.timeType[0].timeTypeCode);
      }
      return date;
    }

    function initFlag(){
      flag = {
        formIsFold : false,
        showTable : false
      };
      return flag;
    }

    function queryFn(){
      var tempParam;
      if(!flag.formIsFold){
        tempParam = setParam();
        CoreLoading.setState(true);
        FileDetailServer.fileDetailQuery(tempParam,function(res){
          if(res.state === '10000' && res.data.length > 0){
            FDViewObjService.setViewObj(res.data,tempParam,param);
            CoreLoading.setState(false);
            flag.showTable = true;
            flag.formIsFold = true;
          }else{
            flag.showTable = '';
            CoreLoading.setState(false);
            CoreService.dialog(res.state);
          }
        });
      }else{
        flag.formIsFold = !flag.formIsFold;
      }
    }

    function setParam(){
      var tempParam = {};
      var format;
      if(param.channelCode){
        tempParam.channelCode = param.channelCode.businessLineCode;
      }else{
        tempParam.channelCode = '';
      }

      if(param.timeType){
        tempParam.timeType = param.timeType.timeTypeCode;
      }else{
        tempParam.timeType = selector.timeType[0].timeTypeCode;
      }
      format = RecAbnormalService.FORMATARRAY[tempParam.timeType];

      if(param.provinceCode){
        tempParam.provinceCode = param.provinceCode.map(function(item){return item.provinceCode;}).join(',');
      }else{
        tempParam.provinceCode = '';
      }
      tempParam.provincial = '1';
      if(param.timeType){
        switch(param.timeType.timeTypeCode){
          case '4':
            tempParam.startTime = param.quarter.startTime.substr(0,4)+'-01-01';
            tempParam.endTime = param.quarter.endTime.substr(0,4)+'-01-01';
            tempParam.startQuarter = param.quarter.startTime.substr(4,1);
            tempParam.endQuarter = param.quarter.endTime.substr(4,1);
            break;
          case '5':
            tempParam.startTime = date.startTime+'-01-01';
            tempParam.endTime = date.endTime+'-01-01';
            break;
          default :
            tempParam.startTime = CoreService.dateFormat(date.startTime,format);
            tempParam.endTime = CoreService.dateFormat(date.endTime,format);
        }
      }else{
        tempParam.startTime = CoreService.dateFormat(date.startTime,format);
        tempParam.endTime = CoreService.dateFormat(date.endTime,format);
      }
      return tempParam;
    }
  }

  function fileDetailViewObj(RecAbnormalService,$timeout,FDSelectorService,CoreService,PublicFn){
    var viewObj = {};
    var chartObj = {};
    return {
      initViewObj : initViewObj,
      initChart : initChart,
      setViewObj : setViewObj
    };

    function initViewObj(){
      viewObj = {
        series:[],
        exportParam:{},
        duration:'',
        title:'',
        isPrepare:false,
        total:{
          unreceivedCount:0,
          delayedTime:0
        },
      };
      return viewObj;
    }

    function initChart(){
      chartObj = echarts.init(document.getElementById('fileDetailChart'));
      return chartObj;
    }

    function setViewObj(data,param,originParam){
      var selectedProvinces = [];
      var selectedBusinessLine;
      var tempData = {};
      var fileDetailChartOpt;
      var busTitle = '';
      var selector = FDSelectorService.selector;
      viewObj.series = [];
      // viewObj.duration = RecAbnormalService.getDuration(param);
      viewObj.duration = PublicFn.fmtDateTitle(param,'timeType');
      viewObj.total.unreceivedCount = 0;
      viewObj.total.delayedTime = 0;

      if(param.channelCode){
        angular.forEach(selector.channelCode,function(item){
          if(param.channelCode === item.businessLineCode){
            selectedBusinessLine = item;
          }
        });
      }else{
        selectedBusinessLine = selector.channelCode;
      }

      if(is.array(selectedBusinessLine)){
        busTitle = selectedBusinessLine.map(function(item){return item.businessLineName;}).join(',');
      }else{
        busTitle = selectedBusinessLine.businessLineName;
      }
      viewObj.title = getTitle(busTitle);

      fileDetailChartOpt = new ChartOpt(viewObj.title);
      if(originParam.provinceCode && originParam.provinceCode.length >= 1){
        selectedProvinces = CoreService.sort(originParam.provinceCode,'provinceCode');
      }else{
        selectedProvinces = selector.provinceCode;
      }

      angular.forEach(selectedProvinces,function(item){
        tempData[item.provinceCode] = {
          unreceivedCount:0,
          delayedTime:0
        };
        fileDetailChartOpt.xAxis[0].data.push(item.provinceName);
      });

      angular.forEach(data,function(item){
        tempData[item.provinceCode].unreceivedCount += Number(item.unreceivedCount);
        tempData[item.provinceCode].delayedTime += Number(item.delayedTime);
        viewObj.total.unreceivedCount += Number(item.unreceivedCount);
        viewObj.total.delayedTime += Number(item.delayedTime);
      });

      angular.forEach(selectedProvinces,function(item){
        fileDetailChartOpt.series[0].data.push(tempData[item.provinceCode].unreceivedCount);
        viewObj.series.push({
          provinceName:item.provinceName,
          provinceCode:item.provinceCode,
          unreceivedCount:tempData[item.provinceCode].unreceivedCount,
          delayedTime:tempData[item.provinceCode].delayedTime
        });
      });
      setChart(fileDetailChartOpt,param);
    }

    function getTitle(busTitle){
      var title = viewObj.duration.replace(/_/g,' 至 ')+busTitle+'文件延迟统计';
      return title;
    }

    function setChart(opt,param){
      chartObj.clear();
      chartObj.setOption(opt);
      $timeout(function(){setExportParam(param);},600);
    }

    function ChartOpt(title){
      this.title = { text: title , x:'center'};
      this.tooltip = { show:true,formatter :'{b}:{c}'};
      this.legend = {show:true,data:['未按时到达次数'],x:'right'};
      this.xAxis = [
        { type: 'category', data: [],axisLabel:{interval:0},splitLine: {show:false}}
      ];
      this.animation = false;
      this.yAxis = [
        { type: 'value', name: '未按时到达次数'}
      ];
      this.series = [
        {
          name: '未按时到达次数', type: 'bar', data: [],
          clickable:false,
          itemStyle:{
            emphasis: {
              color: 'rgba(0,0,0,0)'
            }
          }
        }
      ];
    }

    function setExportParam(param){
      var tempParam = {};
      angular.copy(param,tempParam);
      tempParam.title = viewObj.title;
      tempParam.duration = viewObj.duration;
      tempParam.base64s = [];
      tempParam.base64s.push(chartObj.getDataURL().split(',')[1]);
      viewObj.exportParam = JSON.stringify(tempParam);
      viewObj.isPrepare = true;
    }
  }

})();